$(function () {
    $("#jqGrid").jqGrid({
        url: baseURL + 'sys/stockpurpose/list',
        datatype: "json",
        colModel: [			
			{ label: 'id', name: 'id', index: 'id', width: 50, key: true,hidden:true },
			{ label: '盘点单号', name: 'purposenumber', index: 'purposeNumber', width: 80 }, 			
			{ label: '货架', name: 'shelvesid', index: 'shelvesId', width: 80,formatter: function(cellvalue, options, rowdata) {
                    if(rowdata.shelvesid!=null&&rowdata.shelvesid!=""){
                        var shelvesname = "";

                        $.ajax({
                            type: "POST",
                            async:false,
                            url: baseURL + "sys/goodshelves/info/"+rowdata.shelvesid,
                            success: function(r){
                                shelvesname =r.goodshelves.shelvesname;

                            }
                        });

                        return shelvesname;
                    }else{
                        return '';
                    }


                } },
            { label: '商品数量', name: 'num', index: 'num', width: 80 },
            { label: '盈亏数量', name: 'profitlossnum', index: 'profitLossNum', width: 80 },
            { label: '盈亏金额', name: 'profitlossmoney', index: 'profitLossMoney', width: 80 },
			{ label: '盘点时间', name: 'createtime', index: 'createtime', width: 80 }, 			
			{ label: '操作人', name: 'createuser', index: 'createUser', width: 80,formatter: function(cellvalue, options, rowdata) {
                    if(rowdata.createuser!=null&&rowdata.createuser!=""){
                        var username = "";

                        $.ajax({
                            type: "POST",
                            async:false,
                            url: baseURL + "sys/user/info/"+rowdata.createuser,
                            success: function(r){
                                username =r.user.username;


                            }
                        });

                        return username;
                    }else{
                        return '';
                    }


                } },
			{ label: '备注', name: 'remark', index: 'remark', width: 80 },
            { label: '操作', name: 'sy', width: 70,align:'center',formatter: function(cellvalue, options, rowdata) {
                    return "<a style='cursor:pointer;' onclick='vm.getDetails("+ rowdata.id +")'>" +
                        "详情</a>";
                }}
        ],
		viewrecords: true,
        height: 385,
        rowNum: 10,
		rowList : [10,30,50],
        rownumbers: true, 
        rownumWidth: 25, 
        autowidth:true,
        multiselect: true,
        pager: "#jqGridPager",
        jsonReader : {
            root: "page.list",
            page: "page.currPage",
            total: "page.totalPage",
            records: "page.totalCount"
        },
        prmNames : {
            page:"page", 
            rows:"limit", 
            order: "order"
        },
        gridComplete:function(){
        	//隐藏grid底部滚动条
        	$("#jqGrid").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" }); 
        }
    });
    vm.queryGoodshelves();
});

var vm = new Vue({
	el:'#rrapp',
	data:{
		q:{
            shelvesid:null,
            number:null,
            startime:null,
            endtime:null
		},
        qp:{
            name:null,
            categoryid:null
        },
        showList: true,
        showInfoList:true,
        showAddList:true,
		title: null,
		stockpurpose: {},
        childProduct:[]
	},
	methods: {
		query: function () {
			vm.reload();
		},
        queryProduct: function () {
            vm.reloadProduct();
        },
		add: function(){
			vm.showList = false;
            vm.showAddList = false;
			vm.title = "新增";
			vm.stockpurpose = {};
			vm.getGoodshelves();
		},
		update: function (event) {
			var id = getSelectedRow();
			if(id == null){
				return ;
			}
			vm.showList = false;
            vm.title = "修改";
            
            vm.getInfo(id)
		},
        getDetails:function (id) {
            $.ajax({
                type: "POST",
                async:false,
                url: baseURL + "sys/stockpurpose/infoById/"+id,
                success: function(r){
                    $("#purposenumber").text(r.stockpurpose.purposenumber);
                    $("#createuser").text(r.stockpurpose.createuser);
                    $("#createtime").text(r.stockpurpose.createtime);
                    $("#shelvesnames").text(r.stockpurpose.shelvesname);
                    $("#remark").text(r.stockpurpose.remark==''?'--':r.stockpurpose.remark);
                }
            });

            $("#infoproduct").html("");
            var temp = "";
            $.ajax({
                type: "POST",
                async:false,
                url: baseURL + "sys/stockpurposeitem/infoByShelvesId/"+id,
                success: function(r){
                    var yksl = 0;
                    var hjykje = 0;
                    for(var i=0;i<r.stockpurposeitem.length;i++){
                        yksl += r.stockpurposeitem[i].ykcount;
                        hjykje += r.stockpurposeitem[i].profitlossmoney;
                        temp +="<tr style='height:39px;' ><td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'><img src='"+r.stockpurposeitem[i].productimg+"'></td>" +
                            "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+r.stockpurposeitem[i].productname+"</td>" +
                            "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+r.stockpurposeitem[i].count+"</td>" +
                            "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+r.stockpurposeitem[i].purposecount+"</td>" +
                            "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+r.stockpurposeitem[i].ykcount+"</td>" +
                            "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>￥"+r.stockpurposeitem[i].costprice+"</td>" +
                            "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>￥"+r.stockpurposeitem[i].profitlossmoney+"</td></tr>";
                    }
                    $("#spzl").text(r.stockpurposeitem.length);
                    $("#yksl").text(yksl);
                    $("#hjykje").text(hjykje);
                }
            });
            $("#infoproduct").html(temp);
            vm.showList = false;
            vm.showInfoList = false;


        },
        addProduct: function () {
		    console.log(typeof vm.stockpurpose.shelvesid)
            if(vm.stockpurpose.shelvesid!='' && typeof vm.stockpurpose.shelvesid!='undefined'){
                $("#jqGridAddProudct").jqGrid({
                    url: baseURL + 'sys/product/lowerlist',
                    datatype: "json",
                    colModel: [
                        { label: 'id', name: 'id', index: 'id', width: 50, key: true,hidden:true },
                        { label: '商品名称', name: 'productname', index: 'productName', width: 170 },
                        { label: '分类', name: 'categoryid', index: 'categoryid', width: 225,formatter: function(cellvalue, options, rowdata) {
                                if(rowdata.categoryid!=null&&rowdata.categoryid!=""){
                                    var groupname = "";
                                    var arr = rowdata.categoryid.split(",");
                                    for(var i=0;i<arr.length;i++){
                                        $.ajax({
                                            type: "POST",
                                            async:false,
                                            url: baseURL + "sys/productcategory/info/"+parseInt(arr[i]),
                                            success: function(r){
                                                groupname +=r.productcategory.name;
                                                if(i !=arr.length-1){
                                                    groupname +="/";
                                                }

                                            }
                                        });
                                    }
                                    return groupname;
                                }else{
                                    return '未分组';
                                }


                            } },
                        { label: '创建时间', name: 'createtime', index: 'createtime',width: 170}
                    ],
                    viewrecords: true,
                    height: 385,
                    rowNum: 10,
                    rowList : [10,30,50],
                    rownumbers: true,
                    rownumWidth: 25,
                    autowidth:true,
                    multiselect: true,
                    pager: "#jqGridPagerAddProudct",
                    jsonReader : {
                        root: "page.list",
                        page: "page.currPage",
                        total: "page.totalPage",
                        records: "page.totalCount"
                    },
                    prmNames : {
                        page:"page",
                        rows:"limit",
                        order: "order"
                    },postData:{
                        "shelvesid":vm.stockpurpose.shelvesid
                    },
                    gridComplete:function(){
                        //隐藏grid底部滚动条
                        $("#jqGridPagerAddProudct").closest(".ui-jqgrid-bdiv").css({ "overflow-x" : "hidden" });
                    }
                });
                vm.queryCategory();
                $('#myProductModal').modal();
            }else{
                alert("请选择货架");
            }

        },
        showProduct:function () {
            var grid = $("#jqGridAddProudct");
            var rowKey = grid.getGridParam("selrow");
            if(!rowKey){
                alert("请选择一条记录");
                return ;
            }
            var rows = grid.getGridParam("selarrrow");

            var temp = "";
            $("#goods").html("");
            for(var i=0;i<rows.length;i++){
                var obj = {};
                var isExits = false;
                if(vm.childProduct.length>0){
                    for(var j=0;j<vm.childProduct.length;j++){
                        if(rows[i]==vm.childProduct[j].id){
                            isExits = true;
                        }
                    }
                    if(!isExits){
                        $.ajax({
                            type: "POST",
                            async:false,
                            url: baseURL + "sys/product/info/"+rows[i],
                            success: function(r){
                                obj.id = rows[i];
                                obj.name = grid.getRowData(rows[i]).productname;
                                obj.headimg = r.product.productimg;
                                obj.stock = 10;//库存
                                obj.count = 0;          //盘点后数量
                                obj.ykcount = obj.stock; //盈亏数量
                                vm.childProduct.push(obj);

                            }
                        });

                    }

                }else{
                    $.ajax({
                        type: "POST",
                        async:false,
                        url: baseURL + "sys/product/info/"+rows[i],
                        success: function(r){
                            obj.id = rows[i];
                            obj.name = grid.getRowData(rows[i]).productname;
                            obj.headimg = r.product.productimg;
                            obj.stock = 10;//库存
                            obj.count = 0;          //盘点后数量
                            obj.ykcount = obj.stock; //盈亏数量
                            vm.childProduct.push(obj);

                        }
                    });



                }

            }

            for(var k=0;k<vm.childProduct.length;k++){
                temp +="<tr style='height:39px;' ><td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'><img src='"+vm.childProduct[k].headimg+"'></td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.childProduct[k].name+"</td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);' id='sl"+vm.childProduct[k].id+"'>10</td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>" +
                    "<input type='text' style='width:60px;' id='inputs' value='' oninput=vm.changeInput("+vm.childProduct[k].id+",event)></td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);' class='yk' id='yk"+vm.childProduct[k].id+"'></td>" +
                    "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>" +
                    "<img src='../../statics/img/ico16-delete.png' onclick='vm.removeProduct("+vm.childProduct[k].id+")' style='cursor: pointer'></td></tr>";
            }
            $("#zl").text(vm.childProduct.length);
            $("#goods").append(temp);
            $('#myProductModal').modal("hide");

        },
        removeProduct: function (id) {
            var temp = "";
            $("#goods").html("");
            var childProducttemp = [];
            for(var i=0;i<vm.childProduct.length;i++){
                var obj = {};

                if(vm.childProduct[i].id !=id){
                    $.ajax({
                        type: "POST",
                        async:false,
                        url: baseURL + "sys/product/info/"+vm.childProduct[i].id,
                        success: function(r){
                            obj.id = vm.childProduct[i].id;
                            obj.name = vm.childProduct[i].name;
                            obj.headimg = r.product.productimg;
                            obj.stock = 10;//库存
                            obj.count = 0;          //盘点后数量
                            obj.ykcount = obj.stock; //盈亏数量
                            childProducttemp.push(obj);

                        }
                    });

                    temp +="<tr style='height:39px;' ><td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'><img src='"+vm.childProduct[i].headimg+"'></td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>"+vm.childProduct[i].name+"</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);' id='sl"+vm.childProduct[i].id+"'>10</td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>" +
                        "<input type='text' style='width:60px;' id='inputs' value='' oninput=vm.changeInput("+vm.childProduct[i].id+",event)></td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);' class='yk' id='yk"+vm.childProduct[i].id+"'></td>" +
                        "<td style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);border-left:solid 1px rgb(226, 229, 237);'>" +
                        "<img src='../../statics/img/ico16-delete.png' onclick='vm.removeProduct("+vm.childProduct[i].id+")' style='cursor: pointer'></td></tr>";
                }

            }
            vm.childProduct = childProducttemp;
            $("#zl").text(vm.childProduct.length);
            if(vm.childProduct.length==0){
                temp +="<tr style='height:39px;' ><td colspan='6' style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>您还未选择商品</td></tr>";
            }
            $("#goods").append(temp);
        },
        changeInput: function (id,e) {
		    var sl = $("#sl"+id).text();
		    var v = e.target.value!=''?parseInt(e.target.value):0;
            for(var k=0;k<vm.childProduct.length;k++){
                if(vm.childProduct[k].id == id){
                    vm.childProduct[k].count = v;
                    vm.childProduct[k].ykcount = v-vm.childProduct[k].stock;
                }

            }
            $("#yk"+id).text(v-sl);

        },
        changeShelves:function () {
            $("#goods").html("");
            $("#zl").text(0);
            vm.childProduct = [];
            var temp ="<tr style='height:39px;' ><td colspan='6' style='text-align: center;background-color: #fff!important;border-top:solid 1px rgb(226, 229, 237);'>您还未选择商品</td></tr>";
            $("#goods").append(temp);
        },
        queryCategory: function(){
            $("#p_id").html("");
            $.get(baseURL + "sys/productcategory/alllist", function(r){
                var temp = "<option value=''></option><option value='0'>未分组</option>";
                $.each(r.alllist, function (i) {

                    temp +="<option value='"+r.alllist[i].id+"'>"+r.alllist[i].name+"</option>";

                });
                $("#p_id").append(temp);

            });
        },
		saveOrUpdate: function (event) {
            var flag = false;
            var inp = $(".yk");

            for(var i=0;i<inp.length;i++)
            {
                if(inp[i].text==''||typeof inp[i].text=='undefined')
                {
                    flag = true;
                }
            }
            if(vm.stockpurpose.shelvesid =='' || typeof vm.stockpurpose.shelvesid=='undefined'){
                alert("请选择货架");
            }else if(vm.childProduct.length==0){
                alert("盘点商品不能为空");
            }else if(flag){
                alert("盘点后数量不能为空");
            }else{
                vm.stockpurpose.products = vm.childProduct;
                $.ajax({
                    type: "POST",
                    url: baseURL + "sys/stockpurpose/save",
                    contentType: "application/json",
                    data: JSON.stringify(vm.stockpurpose),
                    success: function(r){
                        if(r.code === 0){
                            alert('操作成功', function(index){
                                vm.reload();
                            });
                        }else{
                            alert(r.msg);
                        }
                    }
                });
            }

		},
		del: function (event) {
			var ids = getSelectedRows();
			if(ids == null){
				return ;
			}
			
			confirm('确定要删除选中的记录？', function(){
				$.ajax({
					type: "POST",
				    url: baseURL + "sys/stockpurpose/delete",
                    contentType: "application/json",
				    data: JSON.stringify(ids),
				    success: function(r){
						if(r.code == 0){
							alert('操作成功', function(index){
								$("#jqGrid").trigger("reloadGrid");
							});
						}else{
							alert(r.msg);
						}
					}
				});
			});
		},
		getInfo: function(id){
			$.get(baseURL + "sys/stockpurpose/info/"+id, function(r){
                vm.stockpurpose = r.stockpurpose;
            });
		},
        queryGoodshelves: function(){
            $("#sheelves_id").html("");
            $.get(baseURL + "sys/goodshelves/alllist", function(r){
                var temp = "<option value=''></option>";
                $.each(r.alllist, function (i) {

                    temp +="<option value='"+r.alllist[i].id+"'>"+r.alllist[i].shelvesname+"</option>";

                });
                $("#sheelves_id").append(temp);

            });
        },
        getGoodshelves: function(){
            $("#shelvesName").html("");
            $.get(baseURL + "sys/goodshelves/alllist", function(r){
                var temp = "<option value=''></option>";
                $.each(r.alllist, function (i) {

                    temp +="<option value='"+r.alllist[i].id+"'>"+r.alllist[i].shelvesname+"</option>";

                });
                $("#shelvesName").append(temp);

            });
        },
		reload: function (event) {
            var startime = $("#startime").val();
            var endtime = $("#endtime").val();
            if((startime!=''&&typeof startime!='undefined')&&(endtime!=''&&typeof endtime!='undefined')){
                var st = new Date(startime).getTime();
                var et = new Date(endtime).getTime();
                if(st>et){
                    alert("开始时间不能大于结束时间");
                    return;
                }
            }
            vm.showList = true;
            vm.showInfoList = true;
            vm.showAddList = true;
            if(endtime!=''&&typeof endtime!='undefined'){
                var date = new Date(new Date(endtime).getTime()+(24*60*60*1000));
                var premonth   = date.getMonth()+1; //获取当前月份(0-11,0代表1月)
                if(premonth<10){
                    premonth = "0"+premonth;
                }
                var preday = date.getDate(); //获取当前日(1-31)
                if(preday<10){
                    preday = "0"+preday;
                }
                endtime = date.getFullYear()+"-"+premonth+"-"+preday;
            }
			var page = $("#jqGrid").jqGrid('getGridParam','page');
			$("#jqGrid").jqGrid('setGridParam',{
                postData:{'shelvesid':vm.q.shelvesid,'number':vm.q.number,'startime':startime,'endtime':endtime},
                page:page
            }).trigger("reloadGrid");
		},
        reloadProduct: function (event) {
            var page = $("#jqGridAddProudct").jqGrid('getGridParam','page');
            $("#jqGridAddProudct").jqGrid('setGridParam',{
                postData:{'name': vm.qp.name,'categoryid':vm.qp.categoryid},
                page:page
            }).trigger("reloadGrid");
        }
	}
});